import Vue from "vue";
import Router from "vue-router";
import layout from "@views/layout";
import store from "@store";

originRouter();
Vue.use(Router);

// 批量读取子路由文件
const modulesFiles = require.context("./modules", false, /\.js$/);
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
    const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, "$1");
    const value = modulesFiles(modulePath);
    modules[moduleName] = value.default;
    return modules;
}, {});

/**
 * @description 路由参数控制
 *
 * @param {array} meta.role - 权限 如：['admin']
 * @param {string} meta.choice - 指向左侧导航栏所属父菜单name
 * @param {boolean} hidden - 隐藏不显示
 * @param {boolean} onlyFirst - 没有二级菜单
 */
export const constantRoutes = [
    {
        path: "/",
        redirect: "/upload",
    },
    {
        name: "login",
        path: "/login",
        meta: { title: "登录" },
        hidden: true,
        component: (resolve) => require(["@views/login"], resolve),
    },
    {
        name: "upload",
        path: "/upload",
        meta: { title: "图片上传" },
        hidden: true,
        component: (resolve) => require(["@views/upload"], resolve),
    },
	{
        name: "cartoo",
        path: "/cartoo",
        meta: { title: "动画列表" },
        hidden: true,
        component: (resolve) => require(["@views/cartoo"], resolve),
    }
];

export const asyncRoutes = [
    {
        name: "staff",
        path: "/staff",
        redirect: "/user/userList",
        meta: { title: "员工系统" },
        component: layout,
        children: modules["staff"],
    },
    {
        name: "roles",
        path: "/roles",
        redirect: "/roles/home",
        meta: { title: "权限", roles: ["admin"] },
        component: layout,
        children: modules["roles"],
    },
    {
        name: "404page",
        path: "/404/page",
        redirect: "/404/home",
        meta: { title: "哎呀，我迷路了" },
        component: layout,
        children: modules["404"],
        hidden: true,
    },
    {
        path: "*",
        redirect: "/404",
    },
];

const createRouter = () =>
    new Router({
        base: "/pc",
        mode: "history",
        routes: constantRoutes,
    });

const router = createRouter();

router.beforeEach((to, from, next) => {
    const token = localStorage.getItem("token");
    store.commit("SET_NAV", store.state.isMobile && store.state.navStatusBol ? false : true);
    if (token) {
        // 用户权限判断
        const { addRouters } = store.state;
        if (addRouters.length) {
            if (to.path === "/" || to.path === "/login") {
                // 三级菜单，寻找当前第一个子菜单里的第一个
                next(addRouters[0].children[0].path);
            } else {
                next();
            }
        } else {
            // localStorage.setItem('roles', JSON.stringify(['admin']));
            let roles = localStorage.getItem("roles");
            roles = roles ? JSON.parse(roles) : [];
            store.dispatch("GenerateRoutes", { roles }).then(() => {
                const { addRouters } = store.state;
                for (let i = 0, len = addRouters.length; i < len; i++) {
                    router.addRoute(addRouters[i]);
                }
                next({ ...to, replace: true });
            });
        }
    } else if (to.path === "/login" || to.path === "/cartoo") {
        next();
    } else {
        next("/login");
    }
});

export default router;

/**
 * @description 阻止点击当前路由报错
 */
export function originRouter() {
    const originalPush = Router.prototype.push;
    Router.prototype.push = function push(location, onResolve, onReject) {
        if (onResolve || onReject) {
            return originalPush.call(this, location, onResolve, onReject);
        }
        return originalPush.call(this, location).catch((err) => err);
    };
}

/**
 * @description 重置路由
 */
export function resetRouter() {
    const newRouter = createRouter();
    router.matcher = newRouter.matcher;
}
